/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.GodownEntry;
import me.zhengjie.modules.system.domain.PurchaseData;
import me.zhengjie.modules.system.domain.PurchaseRequest;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.system.domain.PurchaseRequestDetail;
import me.zhengjie.modules.system.excel.vo.PurchaseRequestDetailVo;
import me.zhengjie.modules.system.repository.PurchaseDataRepository;
import me.zhengjie.modules.system.repository.PurchaseRequestDetailRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.PurchaseRequestRepository;
import me.zhengjie.modules.system.service.PurchaseRequestService;
import me.zhengjie.modules.system.service.dto.PurchaseRequestDto;
import me.zhengjie.modules.system.service.dto.PurchaseRequestQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.PurchaseRequestMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author 李忠臻
* @date 2024-02-20
**/
@Service
@RequiredArgsConstructor
public class PurchaseRequestServiceImpl implements PurchaseRequestService {

    private final PurchaseDataRepository purchaseDataRepository;
    private final PurchaseRequestRepository purchaseRequestRepository;
    private final PurchaseRequestMapper purchaseRequestMapper;
    private final PurchaseRequestDetailRepository purchaseRequestDetailRepository;
    @Override
    public PageResult<PurchaseRequestDto> queryAll(PurchaseRequestQueryCriteria criteria, Pageable pageable){
        Page<PurchaseRequest> page = purchaseRequestRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(purchaseRequestMapper::toDto));
    }

    @Override
    public List<PurchaseRequestDto> queryAll(PurchaseRequestQueryCriteria criteria){
        return purchaseRequestMapper.toDto(purchaseRequestRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public PurchaseRequestDto findById(Long id) {
        PurchaseRequest purchaseRequest = purchaseRequestRepository.findById(id).orElseGet(PurchaseRequest::new);
        ValidationUtil.isNull(purchaseRequest.getId(),"PurchaseRequest","id",id);
        return purchaseRequestMapper.toDto(purchaseRequest);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PurchaseRequest resources) {
        if(purchaseRequestRepository.findByB2b(resources.getB2b()) != null){
            throw new EntityExistException(PurchaseRequest.class,"b2b",resources.getB2b());
        }
        purchaseRequestRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PurchaseRequest resources) {
        PurchaseRequest purchaseRequest = purchaseRequestRepository.findById(resources.getId()).orElseGet(PurchaseRequest::new);
        ValidationUtil.isNull( purchaseRequest.getId(),"PurchaseRequest","id",resources.getId());
        PurchaseRequest purchaseRequest1 = null;
        purchaseRequest1 = purchaseRequestRepository.findByB2b(resources.getB2b());
        if(purchaseRequest1 != null && !purchaseRequest1.getId().equals(purchaseRequest.getId())){
            throw new EntityExistException(PurchaseRequest.class,"b2b",resources.getB2b());
        }
        purchaseRequest.copy(resources);
        purchaseRequestRepository.save(purchaseRequest);
    }

    @Transactional
    @Override
    public void deleteAll(Long[] ids) {
        List<PurchaseRequest> purchaseRequestList = purchaseRequestRepository.findAllById(Arrays.asList(ids));
        List<Long> idList = purchaseRequestList.stream().filter(p->p.getStatus() == 1).map(PurchaseRequest::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(idList)) {
            List<PurchaseData> purchaseDataList = purchaseDataRepository.findByPurchaseRequestIdIn(idList);
            if (purchaseDataList.stream().filter(p->p.getGodownQuantity() > 0).findAny().isPresent()) {
                throw new BadRequestException("删除的采购清单中存在状态为已审核并且已经入库的数据，不能删除！请重新选择");
            }
            purchaseDataRepository.deleteAll(purchaseDataList);
        }
        purchaseRequestRepository.deleteAllById(Arrays.asList(ids));
    }

    @Override
    public void download(List<PurchaseRequestDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PurchaseRequestDto purchaseRequest : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("B2B号", purchaseRequest.getB2b());
            map.put("状态（0：未审核,1：已审核 2：已取消）", purchaseRequest.getStatus());
            map.put("创建者", purchaseRequest.getCreateBy());
            map.put("更新者", purchaseRequest.getUpdateBy());
            map.put("创建日期", purchaseRequest.getCreateTime());
            map.put("更新时间", purchaseRequest.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Transactional
    @Override
    public void pass(Long id) {
        PurchaseRequest purchaseRequest = purchaseRequestRepository.findById(id).orElseGet(PurchaseRequest::new);
        ValidationUtil.isNull( purchaseRequest.getId(),"PurchaseRequest","id", id);
        purchaseRequest.setStatus(1);
        purchaseRequest.setAuditBy(SecurityUtils.getCurrentUser().getUsername());
        purchaseRequest.setAuditTime(new Timestamp(System.currentTimeMillis()));
        purchaseRequestRepository.save(purchaseRequest);
        List<PurchaseRequestDetail> purchaseRequestDetailList = purchaseRequestDetailRepository.findByPurchaseRequestId(id);
        for (PurchaseRequestDetail purchaseRequestDetail : purchaseRequestDetailList) {
            PurchaseData purchaseData = new PurchaseData();
            BeanUtils.copyProperties(purchaseRequestDetail, purchaseData);
            purchaseData.setId(null);
            purchaseData.setB2b(purchaseRequest.getB2b());
            purchaseData.setGodownQuantity(0);
            purchaseData.setOnPassageQuantity(purchaseRequestDetail.getQuantity());
            purchaseDataRepository.save(purchaseData);
        }
    }

    @Override
    public void cancel(Long id) {
        PurchaseRequest purchaseRequest = purchaseRequestRepository.findById(id).orElseGet(PurchaseRequest::new);
        ValidationUtil.isNull( purchaseRequest.getId(),"PurchaseRequest","id", id);
        purchaseRequest.setStatus(2);
        purchaseRequest.setAuditBy(SecurityUtils.getCurrentUser().getUsername());
        purchaseRequest.setAuditTime(new Timestamp(System.currentTimeMillis()));
        purchaseRequestRepository.save(purchaseRequest);
    }

    @Transactional
    @Override
    public void upload(String name, MultipartFile file) {
        //校验采购单文件名是否重复
        List<PurchaseRequest> purchaseRequestList = purchaseRequestRepository.findByFilename(file.getOriginalFilename());
        if (CollectionUtil.isNotEmpty(purchaseRequestList)) {
            throw new BadRequestException("上传的附件文件名称已经存在，请核实后重新上传");
        }

        try {
            List<PurchaseRequestDetailVo> l = EasyExcel.read(file.getInputStream(), PurchaseRequestDetailVo.class, null).sheet().doReadSync();
            Boolean b = l.stream().filter(s -> s.getB2b() == null || "".equals(s.getB2b())).findAny().isPresent();
            if (b) {
                throw new BadRequestException("存在b2b号为空的数据，请补充后重新上传");
            }
            PurchaseRequestDetailVo firstPurchaseRequestDetailVo = l.get(0);
            PurchaseRequest purchaseRequest = new PurchaseRequest();
            purchaseRequest.setB2b(firstPurchaseRequestDetailVo.getB2b());
            purchaseRequest.setStatus(0);
            purchaseRequest.setFilename(file.getOriginalFilename());
            purchaseRequestRepository.save(purchaseRequest);

            for (int i = 0; i < l.size(); i++) {
                PurchaseRequestDetailVo purchaseRequestDetailVo = l.get(i);
                PurchaseRequestDetail purchaseRequestDetail = new PurchaseRequestDetail();
                BeanUtils.copyProperties(purchaseRequestDetailVo, purchaseRequestDetail);
                purchaseRequestDetail.setIndex(i + 1);
                purchaseRequestDetail.setPurchaseRequestId(purchaseRequest.getId());
                purchaseRequestDetail.setExpectedDeliveryDate(new Timestamp(purchaseRequestDetailVo.getExpectedDeliveryDate().getTime()));
                purchaseRequestDetailRepository.save(purchaseRequestDetail);
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMessage());
        }
    }
}